define(function(require, exports, module) {
    require("Dialog");
    require("./Swfupload");
    require("./Main");
	
			
    var ThisPath = require.resolve("./");
	
	
    $.fn.swfupload = function(options) {
        var defaults = {
            id:"",
			size_limit : '2048 KB',		//图片大小限制
	        num_limit : '10',		//数量限制
	        types  : '*.jpg;*.png;*.gif;*.bmp',	//上传图片类型
			button : 'button.png',
            isthumb: false   //设为缩略图     		
        };
        $.extend(defaults, options);
        var id = defaults.id, upload_ul = $("#" + id).find(".J_upload_queue > ul"), //队列ul
        upload_info = $("#" + id).find(".J_upload_info"), //信息
        upload_queue = $("#" + id).find(".J_upload_queue"), PIC_LIMIT = parseInt(defaults.num_limit), swfu = new SWFUpload({
            upload_url:Upload_Config.url,
            flash_url:ThisPath + "Flash/swfupload.swf",
            post_params:{
                uid :Upload_Config.uid,
				sign:Upload_Config.sign,
                csrf_token:2
            },
            file_size_limit:defaults.size_limit,
            file_types:defaults.types,
            file_upload_limit:PIC_LIMIT,
            button_placeholder_id:id.replace("J_upload_", "J_buttonPlaceHolder_"),
            button_width:"100",
            button_height:"32",
            button_cursor:SWFUpload.CURSOR.HAND,
            button_image_url:ThisPath + defaults.button,
            requeue_on_error:true,
            swfupload_load_failed_handler:function() {
                art.dialog({
                    id:"upload_error",
					follow: document.getElementById('J_swfupload_tip'),
                    title:false,  
                    content:"您还没有安装Flash插件,不能上传图片。"
                });
            },
            file_dialog_start_handler:function() {
                upload_queue.show();
				
				
                if (PIC_LIMIT) {
				    
                    if (upload_info.children(".J_count").text() && upload_ul.children().length >= upload_info.children(".J_count").text()) {
                        return;
                    }
                    upload_info.children(".J_count").text(PIC_LIMIT);
                    var pic_li_arr = [];
                    for (i = 1; i <= PIC_LIMIT; i++) {
                        pic_li_arr.push('<li class="J_pic_empty">' + i + "</li>");
                    }
                    upload_ul.prepend(pic_li_arr.join(""));
                } else {
                    upload_info.remove();
                }
            },
            file_queued_handler:function(file) {
				
                //填充图片显示位置
                var empty_box = upload_queue.find("li.J_pic_empty:eq(0)");
				
				
                if (!PIC_LIMIT && !empty_box.length) {
                    //数量不限且无空位
                    upload_ul.append('<li class="J_pic_empty"></li>');
                    empty_box = upload_queue.find("li.J_pic_empty:eq(0)");
                }
                if (empty_box.length) {
                    empty_box.replaceWith('<li id="' + file.id + '" data-pos="' + empty_box.text() + '"><div class="schedule"><em>0%</em></div></li>');
                } else {
                    this.cancelUpload(file.id);
                    //超出则取消上传
					art.dialog({
                            id:"upload_error",
                            title:false,
							follow: document.getElementById('J_swfupload_tip'),
                            content:'数量超出限制'
                        });
                }
            },
            file_queue_error_handler:function(file, errorCode, message) {
                try {
                    var er;
                    switch (errorCode) {
                      case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                        er = '您上传的图片"' + file.name + '"太大了' + "，单张最大限制为: " + this.settings.file_size_limit;
                        break;

                      case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                        er = "请不要上传0字节的文件";
                        break;

                      case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                        er = "错误的文件类型";
                        break;

                      case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                        er = "最多只能上传" + this.settings.file_upload_limit + "张图片";
                        break;

                      default:
					  
					   er = "Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message;
                        break;
                    }
                    if (er) {
                        art.dialog({
                            id:"upload_error",
                            title:false,
							follow: document.getElementById('J_swfupload_tip'),
                            content:er
                        });
                    }
                } catch (ex) {
                    art.dialog({
                        id:"upload_error",
                        title:false,
						follow: document.getElementById('J_swfupload_tip'),
                        content:ex
                    });
                }
            },
            file_dialog_complete_handler:function(numFilesSelected, numFilesQueued) {
                //开始上传
				
                if (numFilesSelected > 1) {}
                this.startUpload();
            },
            
            upload_start_handler:function(file) {
                //开始上传文件前触发的事件处理函数
                try {} catch (ex) {}
                return true;
            },
            upload_progress_handler:function(file, bytesLoaded, bytesTotal) {
                try {
				
                    var percent = Math.ceil(bytesLoaded / bytesTotal * 100);
                    var file_detail = $("#" + file.id);
                    file_detail.find("em").text(percent + "%");
                } catch (ex) {
                    art.dialog({
                        id:"upload_error",
                        title:false,
						follow: document.getElementById('J_swfupload_tip'),
                        content:ex
                    });
                }
            },
            upload_success_handler:function(file, serverData) {
                try {
                    var file_detail = $("#" + file.id);
                    var data = $.parseJSON(serverData);
                    if (data.state == "1") {
                        var _data = data.data;
                        file_detail.data({
                            serverData:_data
                        }).addClass("uploaded");
						
						  var input= (PIC_LIMIT==1) ? '<input type="hidden" name="'+id.replace("J_upload_", "")+'" value="'+_data.attachurl+'" />' : '<input type="hidden" name="'+id.replace("J_upload_", "")+'[]" value="'+_data.attachurl+'" /><input type="hidden" name="'+id.replace("J_upload_", "")+'_alt[]" value="'+_data.name+'" />';
						  
						  input+='<span class="swf-thumb J_dialog_pic" data="'+_data.attachurl+'">'+_data.name+'</span>';
						   
						  

                        file_detail.html('<a class="del J_upload_del" href="#">删除</a><img title="' + _data.name + '" src="' + _data.attachurl + '" width="96" />'+input+'');
                        //数量
                        var count = upload_info.children(".J_count");
                        //统计
                        count.text(count.text() - 1);
                    } else {
                        file_detail.replaceWith('<li class="J_pic_empty">' + file_detail.data("pos") + "</li>");
                        art.dialog({
                            id:"upload_error",
                            title:false,
							follow: document.getElementById('J_swfupload_tip'),
                            content:data.message
                        });
                        //出错 队列-1
                        var stats = swfu.getStats();
                        stats.successful_uploads--;
                        swfu.setStats(stats);
                        return;
                    }
                } catch (ex) {
                    art.dialog({
                        id:"upload_error",
                        title:false,
						follow: document.getElementById('J_swfupload_tip'),
                        content:'上传出错'
                    });
                }
            },
            upload_complete_handler:function(file) {
                //完成
                try {
                    //如果上传完成后，还有未上传的队列，那和继续自动上传
                    if (this.getStats().files_queued === 0) {} else {
                        this.startUpload();
                    }
                } catch (ex) {
				
                    art.dialog({
                        id:"upload_error",
                        title:false,
						follow: document.getElementById('J_swfupload_tip'),
                        content:ex
                    });
                }
            },
            queue_complete_handler:function() {}
        });
        //删除
        upload_queue.on("click", "a.J_upload_del", function(e) {
            e.preventDefault();
            var li = $(this).parents("li"), pos = li.index() + 1, uploaded_last = upload_queue.find("li.uploaded:last");
            if (uploaded_last.index() + 1 !== pos) {
                //删除的不是最后一张
                li.insertAfter(uploaded_last);
                pos = li.index() + 1;
            }
            li.replaceWith('<li class="J_pic_empty" data-pos="' + pos + '">' + pos + "</li>");
            restLimit();
        });
        //队列数减1
        function restLimit() {
            var stats = swfu.getStats();
            stats.successful_uploads--;
            swfu.setStats(stats);
            var count = upload_info.children(".J_count");
            //统计
            count.text(parseInt(count.text()) + 1);
        }
		
    };
});